package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func RequestGET(uri string, res interface{}) (err error) {
	response, err := http.Get(uri)
	if err != nil {
		err = fmt.Errorf("http.Get err, %+v", err)
		return
	}
	defer response.Body.Close()
	err = parseResponse(response, res)
	return
}

func RequestPOST(uri string, requestData map[string]string, res interface{}) (err error) {
	data := url.Values{}
	for k, v := range requestData {
		data.Add(k, v)
	}
	response, err := http.PostForm(uri, data)
	if err != nil {
		err = fmt.Errorf("http.Get err, %+v", err)
		return
	}
	defer response.Body.Close()
	err = parseResponse(response, res)
	return
}

func parseResponse(response *http.Response, data interface{}) (err error) {
	content, err := ioutil.ReadAll(response.Body)
	if err != nil {
		err = fmt.Errorf("ioutil.ReadAll err, %+v", err)
		return
	}
	if response.StatusCode != 200 {
		err = fmt.Errorf("response.StatusCode != 200 code:%d, body:%s", response.StatusCode, string(content))
		return
	}
	err = json.Unmarshal(content, &data)
	if err != nil {
		err = fmt.Errorf("json.Unmarshal err, %+v", err)
		return
	}
	return
}
